<?php
namespace app\admin\controller;
use function MongoDB\BSON\toJSON;
use think\Db;
use clt\Leftnav;
use app\admin\model\Admin;
use app\admin\model\AuthGroup;
use app\admin\model\authRule;
use think\facade\Request;
use think\Validate;
class Auth extends Common
{
    //管理员列表
    public function adminList(){
        if(Request::isAjax()){
            $val=input('val');
            $url['val'] = $val;
            $this->assign('testval',$val);
            $map='';
            if($val){
                $map['username|email|tel']= array('like',"%".$val."%");
            }
            if (session('aid')!=1){
                $map='admin_id='.session('aid');
            }
            $list=Db::table(config('database.prefix').'admin')->alias('a')
                ->join(config('database.prefix').'auth_group ag','a.group_id = ag.group_id','left')
                ->field('a.*,ag.title')
                ->where($map)
                ->select();
            return $result = ['code'=>0,'msg'=>'获取成功!','data'=>$list,'rel'=>1];
        }
        return view();
    }

    public function adminAdd(){
        if(Request::isAjax()){
            $data = input('post.');
            $check_user = Admin::get(['username'=>$data['username']]);
            if ($check_user) {
                return $result = ['code'=>0,'msg'=>'用户已存在，请重新输入用户名!'];
            }
            $data['pwd'] = input('post.pwd', '', 'md5');
            $data['add_time'] = time();
            $data['ip'] = request()->ip();
            //验证
            $msg = $this->validate($data,'app\admin\validate\Admin');
            if($msg!='true'){
                return $result = ['code'=>0,'msg'=>$msg];
            }
            //单独验证密码
            $checkPwd = Validate::make([input('post.pwd')=>'require']);
            if (false === $checkPwd) {
                return $result = ['code'=>0,'msg'=>'密码不能为空！'];
            }
            //添加
            if (Admin::create($data)) {
                return ['code'=>1,'msg'=>'管理员添加成功!','url'=>url('adminList')];
            } else {
                return ['code'=>0,'msg'=>'管理员添加失败!'];
            }
        }else{
            $auth_group = AuthGroup::all();
            $this->assign('authGroup',$auth_group);
            $this->assign('title',lang('add').lang('admin'));
            $this->assign('info','null');
            $this->assign('selected', 'null');
            return view('adminForm');
        }
    }
    //删除管理员
    public function adminDel(){
        $admin_id=input('post.admin_id');
        if (session('aid')==1){
            Admin::where('admin_id','=',$admin_id)->delete();
            return $result = ['code'=>1,'msg'=>'删除成功!'];
        }else{
            return $result = ['code'=>0,'msg'=>'您没有删除管理员的权限!'];
        }
    }
    //修改管理员状态
    public function adminState(){
        $id=input('post.id');
        $is_open=input('post.is_open');
        if (empty($id)){
            $result['status'] = 0;
            $result['info'] = '用户ID不存在!';
            $result['url'] = url('adminList');
            return $result;
        }
        db('admin')->where('admin_id='.$id)->update(['is_open'=>$is_open]);
        $result['status'] = 1;
        $result['info'] = '用户状态修改成功!';
        $result['url'] = url('adminList');
        return $result;
    }
    //更新管理员信息
    public function adminEdit(){
        if(request()->isPost()){
            $data = input('post.');
            $pwd=input('post.pwd');
            $map[] = ['admin_id','<>',$data['admin_id']];
            $where['admin_id'] = $data['admin_id'];

            if($data['username']){
                $map[] = ['username','=',$data['username']];
                $check_user = Admin::where($map)->find();
                if ($check_user) {
                    return $result = ['code'=>0,'msg'=>'用户已存在，请重新输入用户名!'];
                }
            }
            if ($pwd){
                $data['pwd']=input('post.pwd','','md5');
            }else{
                unset($data['pwd']);
            }
            $msg = $this->validate($data,'app\admin\validate\Admin');
            if($msg!='true'){
                return $result = ['code'=>0,'msg'=>$msg];
            }
            Admin::update($data,$where);
            if( $data['admin_id'] == session('aid')){
                session('username',$data['username']);
                $avatar = $data['avatar']==''?'/static/admin/images/0.jpg':$data['avatar'];
                session('avatar',$avatar);
            }
            return $result = ['code'=>1,'msg'=>'管理员修改成功!','url'=>url('adminList')];
        }else{
            $auth_group = AuthGroup::all();
            $admin = new Admin();
            $info = $admin->getInfo(input('admin_id'));
            $this->assign('info', json_encode($info,true));
            $this->assign('authGroup',$auth_group);
            $this->assign('title',lang('edit').lang('admin'));
            return view('adminForm');
        }
    }


    /*-----------------------角色管理----------------------*/

    /**
     * 角色列表
     * @return array|\think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function adminGroup(){
        if(request()->isPost()){
            // $list = AuthGroup::all();
            $list = Db::name('teacher_position')->where('is_del',0)->select();
            if (! empty($list)) {
                foreach ($list as $k => $v) {
                    $list[$k]['create_time'] = toDate($v['create_time']);
                    $list[$k]['update_time'] = toDate($v['update_time']);
                }
            }
            return $result = ['code'=>0,'msg'=>'获取成功!','data'=>$list,'rel'=>1];
        }
        return view();
    }


    /**
     * 添加角色
     * @return mixed
     */
    public function groupAdd(){
        if(request()->isPost()){
            $data=input('post.');
            $data['create_time']=time();
            $data['update_time']=time();
            $data['add_parentname'] = session('username');
            $re = Db::name('teacher_position')->insert($data);
            $log = [
                'content'=>'角色添加名称'.$data['position_name']
            ];
            $wed = new Weblog();
            $res = $wed->insert($log);
            if ($re && $res){
                $this->success('角色添加成功','adminGroup');
            }else{
                $this->error('角色添加失败');
            }

        }else{
            $this->assign('title','添加角色');
            $this->assign('info','null');
            return $this->fetch('groupForm');
        }
    }

    /**
     * 修改角色
     * @return mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function groupEdit(){
        if(request()->isPost()) {
            $data=input('post.');
            $position_id = input('id');

            $re = Db::name('teacher_position')->where('position_id',$position_id)->update(['position_name'=>$data['position_name'],'update_time'=>time()]);
            $position_name = Db::name('teacher_position')->where('position_id',$position_id)->value('position_name');
            $log = [
                'content'=>'修改角色名称'.$position_name
            ];
            $wed = new Weblog();
            $res = $wed->insert($log);
            if ($re && $res){
                $this->success('角色修改成功','adminGroup');
            }else{
                $this->error('角色修改失败');
            }

        }else{
            $position_id = input('id');
            $info = Db::name('teacher_position')->where('position_id',$position_id)->find();
            $this->assign('info', json_encode($info,true));
            $this->assign('position_name','编辑角色');
            return $this->fetch('groupForm');
        }
    }


    /**
     * 角色状态修改
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function groupState(){

        $position_id=input('post.id');
        $status=input('post.status');

        if (empty($position_id)){
            $this->error('角色ID不存在');
        }

        $re = Db::name('teacher_position')->where('position_id',$position_id)->update(['status'=>$status,'update_time'=>time()]);
        $position_name = Db::name('teacher_position')->where('position_id',$position_id)->value('position_name');
        $log = [
            'content'=>'修改角色状态'.$position_name
        ];
        $wed = new Weblog();
        $res = $wed->insert($log);
        if ($re && $res){
            $this->success('角色状态修改成功');
        }else{
            $this->error('角色状态修改失败');
        }

    }

    /**
     * 删除角色
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function groupDel(){

        $re = Db::name('teacher_position')->where('position_id',input('id'))->update(['is_del'=>1]);
        $position_name =Db::name('teacher_position')->where('position_id',input('id'))->value('position_name');
        $log = [
            'content'=>'删除角色'.$position_name
        ];
        $wed = new Weblog();
        $res = $wed->insert($log);
        if ($re && $res){
            $this->success('删除成功!');
        }else{
            $this->error('删除失败!');
        }

    }


    //角色配置权限的展示
    public function groupAccess(){
        $nav = new Leftnav();
        $admin_rule=db('auth_rule')->field('id,pid,title')->order('sort asc')->select();
        $rules = db('teacher_position')->where('position_id',input('id'))->value('rules');
        $arr = $nav->auth($admin_rule,$pid=0,$rules);
        $arr[] = array(
            "id"=>0,
            "pid"=>0,
            "title"=>"全部",
            "open"=>true
        );
        $this->assign('data',json_encode($arr,true));
        return $this->fetch();
    }

    /**
     * 权限配置操作
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function groupSetaccess(){
        $rules = input('post.rules');
        if(empty($rules)){
            return array('msg'=>'请选择权限!','code'=>0);
        }
        $data = input('post.');

        $where['position_id'] = $data['position_id'];

        $re = Db::name('teacher_position')->where('position_id',$where['position_id'])->update($data);
        $position_name = Db::name('teacher_position')->where('position_id',$where['position_id'])->value('position_name');
        $log = [
            'content'=>'权限配置'.$position_name
        ];
        $wed = new Weblog();
        $res = $wed->insert($log);
        if ($re && $res){
            $this->success('权限配置成功','adminGroup');
        }else{
            $this->error('保存错误');
        }
    }


    /**
     * 职务分配
     * @return mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function groupAssess(){
        $position_id = (int)input('position_id');

        if (request()->isAjax()) {

            $data = input('post.');

            $data['update_time'] = time();
            $data['performance_cate_ids'] = serialize($data['performance_cate_ids']);
            $re = Db::name('teacher_position')->update($data);
            $user = Db::name('teacher_position')->where(['position_id'=>$data['position_id']])->find();
            $log = [
                'content'=>'编辑职务'.$user['title']
            ];

            $wed = new Weblog();
            $wed->insert($log);

            if(!$re){
                $this->error('编辑失败');
            }
            $this->success("编辑成功",'adminGroup');

        }

        $timus = '';
        $user = Db::name('teacher_position')->where(['position_id'=>$position_id])->find();
        if($user['performance_cate_ids']){
            $ids = implode(',',unserialize($user['performance_cate_ids']));
            $cates = Db::name('performance_cate')->field('cate_id,title')->where('cate_id','in',$ids)->select();
        }
        $this->assign('cate_id',$position_id);
        $this->assign('timus',$cates);
        return $this->fetch('group_assess');

    }

    function cate_list(){
        if (request()->isAjax()) {

            $page =input('page',1);
            $pageSize =input('limit',config('pageSize'));

            $list = Db::name('performance_cate')
                ->where('is_del',0)
                ->order('create_time desc')
                ->paginate(array('list_rows'=>$pageSize,'page'=>$page))
                ->toArray();

            if (!empty($list)) {
                foreach ($list['data'] as $k => $v) {
                    $list['data'][$k]['create_time'] = toDate($v['create_time']);
                }
            }

            return $result = ['code'=>0,'msg'=>'成功!','data'=>$list['data'],'count'=>$list['total'],'rel'=>1];
        }

    }




    /********************************权限管理*******************************/
    public function adminRule(){
        if(request()->isPost()){
            $nav = new Leftnav();
            $arr = cache('authRuleList');
            if(!$arr){
                $authRule = authRule::all(function($query){
                    $query->order('sort', 'asc');
                });
                $arr = $nav->menu($authRule);
                cache('authRuleList', $arr, 3600);
            }
            return $result = ['code'=>0,'msg'=>'获取成功!','data'=>$arr,'rel'=>1];
        }
        return view();
    }
    public function ruleAdd(){
        if(request()->isPost()){
            $data = input('post.');
            $data['addtime'] = time();
            authRule::create($data);
            cache('authRule', NULL);
            cache('authRuleList', NULL);
            return $result = ['code'=>1,'msg'=>'权限添加成功!','url'=>url('adminRule')];
        }else{
            $nav = new Leftnav();
            $arr = cache('authRuleList');
            if(!$arr){
                $authRule = authRule::all(function($query){
                    $query->order('sort', 'asc');
                });
                $arr = $nav->menu($authRule);
                cache('authRuleList', $arr, 3600);
            }
            $this->assign('admin_rule',$arr);//权限列表
            return $this->fetch();
        }
    }
    public function ruleOrder(){
        $auth_rule=db('auth_rule');
        $data = input('post.');
        if($auth_rule->update($data)!==false){
            cache('authRuleList', NULL);
            cache('authRule', NULL);
            return $result = ['code'=>1,'msg'=>'排序更新成功!','url'=>url('adminRule')];
        }else{
            return $result = ['code'=>0,'msg'=>'排序更新失败!'];
        }
    }
    //设置权限菜单显示或者隐藏
    public function ruleState(){
        $id=input('post.id');
        $menustatus=input('post.menustatus');
        if(db('auth_rule')->where('id='.$id)->update(['menustatus'=>$menustatus])!==false){
            cache('authRule', NULL);
            cache('authRuleList', NULL);
            return ['status'=>1,'msg'=>'设置成功!'];
        }else{
            return ['status'=>0,'msg'=>'设置失败!'];
        }
    }
    //设置权限是否验证
    public function ruleTz(){
        $id=input('post.id');
        $authopen=input('post.authopen');
        if(db('auth_rule')->where('id='.$id)->update(['authopen'=>$authopen])!==false){
            cache('authRule', NULL);
            cache('authRuleList', NULL);
            return ['status'=>1,'msg'=>'设置成功!'];
        }else{
            return ['status'=>0,'msg'=>'设置失败!'];
        }
    }
    public function ruleDel(){
        authRule::destroy(['id'=>input('param.id')]);
        cache('authRule', NULL);
        cache('authRuleList', NULL);
        return $result = ['code'=>1,'msg'=>'删除成功!'];
    }

    public function ruleEdit(){
        if(request()->isPost()) {
            $datas = input('post.');
            if(authRule::update($datas)) {
                cache('authRule', NULL);
                cache('authRuleList', NULL);
                return json(['code' => 1, 'msg' => '保存成功!', 'url' => url('adminRule')]);
            } else {
                return json(['code' => 0, 'msg' =>'保存失败！']);
            }
        }else{
            $admin_rule = authRule::get(function($query){
                $query->where(['id'=>input('id')])->field('id,href,title,icon,sort,menustatus');
            });
            $this->assign('rule',$admin_rule);
            return $this->fetch();
        }
    }
}